<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute-lt flex-x-end p-3 w-full">
      <el-switch v-model="isDark" inline-prompt :active-icon="Moon" :inactive-icon="Sunny" @change="toggleTheme" />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录/注册表单 -->
    <div class="card-container" :class="{ 'is-flipped': isRegister }">
      <el-card class="card-face card-front !border-none !bg-transparent !rounded-4% w-100 <sm:w-85">
        <div class="text-center relative">
          <h2>用户登录</h2>
        </div>

        <el-form ref="loginFormRef" :model="loginData" :rules="loginRules" class="login-form">
          <!-- 用户名 -->
          <el-form-item prop="username">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="user" class="mx-2" />
              <el-input ref="username" v-model="loginData.username" :placeholder="$t('login.username')" name="username"
                size="large" class="h-[48px]" />
            </div>
          </el-form-item>

          <!-- 密码 -->
          <el-tooltip :visible="isCapslock" :content="$t('login.capsLock')" placement="right">
            <el-form-item prop="password">
              <div class="flex-y-center w-full">
                <svg-icon icon-class="lock" class="mx-2" />
                <el-input v-model="loginData.password" :placeholder="$t('login.password')" type="password"
                  name="password" @keyup="checkCapslock" @keyup.enter="handleLogin" size="large" class="h-[48px] pr-2"
                  show-password />
              </div>
            </el-form-item>
          </el-tooltip>

          <!-- 验证码 -->
          <el-form-item prop="captchaCode">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="captcha" class="mx-2" />
              <el-input v-model="loginData.captchaCode" auto-complete="off" size="large" class="flex-1"
                :placeholder="$t('login.captchaCode')" @keyup.enter="handleLogin" />

              <el-image @click="getCaptcha" :src="captchaBase64"
                class="rounded-tr-md rounded-br-md cursor-pointer h-[48px]" />
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-button :loading-icon="Eleme" type="primary" size="large" class="w-full" @click.prevent="handleLogin"
            :loading="loading" round>{{
        $t("login.login") }}
          </el-button>

          <div class="text-center mt-4">
            <el-link type="primary" @click="toggleForm">还没有账号？立即注册</el-link>
          </div>
        </el-form>
      </el-card>
      <el-card class="card-face card-back !border-none !bg-transparent !rounded-4% w-100 <sm:w-85">
        <div class="text-center relative">
          <h2>注册账号</h2>
        </div>
        <el-form ref="registerFormRef" :model="registerData" :rules="registerRules" class="login-form">
          <el-form-item prop="username">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="user" class="mx-2" />
              <el-input v-model="registerData.username" placeholder="请输入用户名" name="username" size="large"
                class="h-[48px]" />
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="lock" class="mx-2" />
              <el-input v-model="registerData.password" placeholder="请输入密码" type="password" name="password" size="large"
                class="h-[48px] pr-2" show-password />
            </div>
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="lock" class="mx-2" />
              <el-input v-model="registerData.confirmPassword" placeholder="请确认密码" type="password"
                name="confirmPassword" size="large" class="h-[48px] pr-2" show-password />
            </div>
          </el-form-item>
          <el-button type="primary" size="large" class="w-full" @click.prevent="handleRegister"
            :loading="registerLoading" round>注册</el-button>
          <div class="text-center mt-4">
            <el-link type="primary" @click="toggleForm">已有账号？返回登录</el-link>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import { ThemeEnum } from "@/enums/ThemeEnum";
import router from "@/router";
import { useSettingsStore, useUserStore } from "@/store";
import { Eleme, Moon, Sunny } from "@element-plus/icons-vue";
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";

interface RegisterData {
  username: string;
  password: string;
  confirmPassword: string;
}

// Stores
const userStore = useUserStore();
const settingsStore = useSettingsStore();

// Internationalization
const { t } = useI18n();

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const registerFormRef = ref(ElForm); // 注册表单ref
const { height } = useWindowSize();

const isRegister = ref(false); // 是否显示注册表单
const registerLoading = ref(false); // 注册按钮loading

const registerData = ref<RegisterData>({
  username: "",
  password: "",
  confirmPassword: "",
});

const loginData = ref<LoginData>({
  username: "",
  password: "",
});

const loginRules = computed(() => {
  return {
    username: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.username.required"),
      },
    ],
    password: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.password.required"),
      },
      {
        min: 6,
        message: t("login.message.password.min"),
        trigger: "blur",
      },
    ],
    captchaCode: [
      {
        required: true,
        trigger: "blur",
        message: t("login.message.captchaCode.required"),
      },
    ],
  };
});

const registerRules = computed(() => {
  return {
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 3, message: "用户名长度不能小于3位", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
    ],
    confirmPassword: [
      { required: true, message: "请确认密码", trigger: "blur" },
      {
        validator: (rule: any, value: string, callback: Function) => {
          if (value !== registerData.value.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur",
      },
    ],
  };
});

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi().then(({ data }) => {
    loginData.value.captchaKey = data.captchaKey;
    captchaBase64.value = data.captchaBase64;
  });
}

/**
 * 登录
 */
const route = useRoute();
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      userStore
        .login(loginData.value)
        .then(() => {
          const query: LocationQuery = route.query;
          const redirect = (query.redirect as LocationQueryValue) ?? "/";
          const otherQueryParams = Object.keys(query).reduce(
            (acc: any, cur: string) => {
              if (cur !== "redirect") {
                acc[cur] = query[cur];
              }
              return acc;
            },
            {}
          );

          router.push({ path: redirect, query: otherQueryParams });
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 主题切换
 */

const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};

/**
 * 根据屏幕宽度切换设备模式
 */
watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/**
 * 检查输入大小写
 */
function checkCapslock(event: KeyboardEvent) {
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

// 切换登录/注册表单
const toggleForm = () => {
  isRegister.value = !isRegister.value;
};

// 处理注册
const handleRegister = () => {
  registerFormRef.value.validate((valid: boolean) => {
    if (valid) {
      registerLoading.value = true;
      console.log(registerData.value)
      userStore.register(registerData.value).then(
        () => {
          ElMessage.success("注册成功");
          // 将注册的用户名和密码填充到登录表单
          loginData.value.username = registerData.value.username;
          loginData.value.password = registerData.value.password;
          // 清空注册表单
          registerData.value.username = "";
          registerData.value.password = "";
          registerData.value.confirmPassword = "";
          isRegister.value = false;
          registerLoading.value = false;
        }
      ).catch()
        .finally(() => {
          registerLoading.value = false;
        })
    }
  });
};

onMounted(() => {
  getCaptcha();
});
</script>

<style lang="scss" scoped>
html.dark .login-container {
  background:
    url("@/assets/images/login-bg-dark.jpg") no-repeat center/cover;
}

.login-container {
  overflow-y: auto;
  background:
    url("@/assets/images/login-bg.jpg") no-repeat center/cover;

  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .card-container {
    position: relative;
    width: 100%;
    max-width: 400px;
    height: 500px;
    perspective: 1000px;
    transform-style: preserve-3d;
  }

  .card-face {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    transition: transform 0.6s;
    background: rgba(var(--el-bg-color-rgb), 0.1) !important;
    backdrop-filter: blur(3px);
    -webkit-backdrop-filter: blur(5px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.8);
  }

  .card-front {
    transform: rotateY(0deg);
  }

  .card-back {
    transform: rotateY(180deg);
  }

  .card-container.is-flipped {
    .card-front {
      transform: rotateY(-180deg);
    }

    .card-back {
      transform: rotateY(0deg);
    }
  }

  .login-form {
    padding: 30px 10px;
  }
}

.el-form-item {
  background: rgba(var(--el-bg-color-rgb), 0.7);
  border: 1px solid rgba(var(--el-border-color-rgb), 0.2);
  border-radius: 5px;
  margin-bottom: 24px;
  transition: all 0.3s ease;
  position: relative;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);

  &:hover {
    transform: translateY(-2px);
    background: rgba(var(--el-bg-color-rgb), 0.8);
  }
}

:deep(.el-input) {
  .el-input__wrapper {
    padding: 0;
    background-color: transparent;
    box-shadow: none;

    &.is-focus,
    &:hover {
      box-shadow: none !important;
    }

    input:-webkit-autofill {
      /* 通过延时渲染背景色变相去除背景颜色 */
      transition: background-color 1000s ease-in-out 0s;
    }
  }
}
</style>
